<?php
require_once '../library/Zend/File/Transfer/Adapter/Http.php';
require_once '../library/Zend/Captcha/Image.php';
require_once '../library/Zend/Loader.php';
require_once '../library/Util/SSO.php';
require_once '../library/Util/OAuth2.php';
class Util {

    public static function ssoLogin($serverUrl, $returnUrl, $requireData, $optionalData){
        $sso = new MCore_SSO();
        $result = $sso->checkSSO($serverUrl, $returnUrl, $requireData, $optionalData);
        return $result;        
    }

    public static function ssoComplete($returnUrl, $requireData, $optionalData){
        $sso = new MCore_SSO();
        $result = $sso->complete($returnUrl, $requireData, $optionalData);
        return $result;
    }

    public static function ssoCheckState($serverUrl, $uid, $sid){
        $sso = new MCore_SSO();
        $result = $sso->checkLoginStatus($serverUrl, $uid, $sid);
        return $result;
    }


    public static function oauthGetApi($url, $params = null, $method = 'GET'){
        $oauth = new MCore_OAuth();
        $result = $oauth->getApi($url, $params, $method);
        return $result;
    }
    // public static function ssoLoginStatus($serverUrl){
    //     $sso = new MCore_SSO();
    //     $result = $sso->checkLoginStatus($serverUrl);
    //     return $result;
    // }    
	public static function is_interger($int){
       
        // First check if it's a numeric value as either a string or number
        if(is_numeric($int) === TRUE){
           
            // It's a number, but it has to be an integer
            if((int)$int == $int){

                return TRUE;
               
            // It's a number, but not an integer, so we fail
            }else{
           
                return FALSE;
            }
       
        // Not a number
        }else{
       
            return FALSE;
        }
    }
    
    public static function is_valid_email($email)
    {
    	$regexp = "/^[A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";
		if (preg_match($regexp, $email))
		return true; 
		else 
		return false;
    // return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
    }
    
	public static function get_time_now(){
    	return time();
    }
    
    public static function change_int_to_date($int){
    	return gmdate("g:i A d-m-Y", $int);
    }
    
    public static function change_date_to_int($month, $day, $year){
    	return mktime(0, 0, 0, $month, $day, $year)+7*3600;
    }
    
	public function makeDays($stime){
		
		
		$_stime= $stime; // -7 tieng
		//$date = date("D",$_stime);
		/*
		switch ($date)
		{
 		    case "Mon":
		    $date = "Thứ hai";
		    break;
	   		case "Tue":
    		$date = "Thứ ba";
		    break;		 
 		    case "Wed":
		    $date = "Thứ tư°";
		    break;
	   		case "Thu":
    		$date = "Thứ năm";
		    break; 		    
		    case "Fri":
		    $date = "Thứ sáu";
		    break;
	   		case "Sat":
    		$date = "Thứ bảy";
		    break;
	   		case "Sun":
    		$date = "Chủ nhật";
		    break;
		}
		$date = $date." , ".date("d-m-Y , H:i A",$_stime);
		*/
		$date = date("d-m-Y , H:i:s",$_stime);
						
		return $date; 
	}
	
/**
     * Create thubnail image
     * 
     * If there is no exsiting thumbnail image, new thubnal image will be created
     * If no width or height is determined, default thumbnail image will be returned
     * 
     * 
     * @param string $source             Path of full image path from project directory. Example: "media/userfiles/images/..." 
     * @param int    $thumbWidth         The width of thumbnail image. If $width is null, the ratio will be keep 
     * @param int    $thumbHeight        The heigh of thumbnail image. If $height is null, the ratio will be keep
     * @param string $backgroundColor    Background of new image in the case image is changed ratio
     */
    public static function getThumbImage($source, $storeId = null , $thumbWidth = null, $thumbHeight = null, $backgroundColor = '#000000') 
    {
        $source = urldecode($source);
        /**
         * Is invalid image?
         */
        if (! is_file($source)) {
            return $source;
        }
        /**
         * Parse the path of new thumbnail image
         */
        if (null == $thumbWidth && null == $thumbHeight) {
            /**
             * Load default config
             */
            include_once 'Nine/Registry.php';
            $config = @Nine_Registry::getConfig('defaultThumbnailImageSize');
            $config = explode('x', $config);
            if (empty($config) || 2 != count($config)) {
                throw new Exception("'defaultThumbnailImageSize'  in config.php file is missing or incorrect.");
            }
            $thumbWidth  = intval($config[0]);
            $thumbHeight = intval($config[1]);
        }
        $thumbImgPath = "media/thumb/estore{$storeId}/{$thumbWidth}xRate/" 
                      . str_replace('/', '_', $source);
        /**
         * Image is exisiting?
         */
        if (is_file($thumbImgPath)) {
            return $thumbImgPath;
        }
        /************************************************************************************
         * Create thumbnail image
         ************************************************************************************/
        /**
         * Create thumbnal dicrectory
         */
        $folderPath = substr($thumbImgPath, 0, strrpos($thumbImgPath, '/'));
        Nine_Folder::mkDirIfNotExist($folderPath);
        /**    
         * Detect type of image
         */
        $info = getimagesize($source);
        $extension = strtolower($info['mime']);
        switch ($extension) {
            case 'image/jpeg':
                $imgFromFunc = 'imagecreatefromjpeg';
                $imageFunc   = 'imagejpeg';
                break;
            case 'image/png':
                $imgFromFunc = 'imagecreatefrompng';
                $imageFunc   = 'imagepng';
                break;
            case 'image/gif':
                $imgFromFunc = 'imagecreatefromgif';
                $imageFunc   = 'imagegif';
                break;
            default:
                return $source;
        }
        $img = $imgFromFunc("{$source}");
        /**
         * Load image and get image size
         */
        $width = imagesx($img);
        $height = imagesy($img);
        /**
         * Caculate thumbnail image size
         */
        if (null == $thumbWidth) {
            /**
             * Missing width param
             */
            $thumbWidth = floor($width * ( $thumbHeight / $height ));
        }
        if (null == $thumbHeight) {
            /**
             * Missing height param
             */
            $thumbHeight = floor($height * ( $thumbWidth / $width ));
        }
        /**
         * Calculate scaled image size
         */
        /**
         * Resized with width
         */
        $sWidth = $thumbWidth;
        $sHeight = $thumbHeight;
        //$sHeight = floor($height * ( $thumbWidth / $width ));
        /**
         * Resized with height
         */
        //if ($sHeight > $thumbHeight) {
            //$sWidth = floor($thumbWidth * ( $thumbHeight / $sHeight ));
            //$sHeight = $thumbHeight;
        //}
        /**
         * Calculate postion
         */
        $dstX = floor(($thumbWidth - $sWidth)/2); 
        $dstY = floor(($thumbHeight - $sHeight)/2); 
        /**
         * Valid X,Y
         */
        if ($dstX < 0) {
            $dstX = 0;
        }
        if ($dstY < 0) {
            $dstY = 0;
        }
//        echo "$dstX, $dstY";die;
//        echo "$thumbWidth x $thumbHeight";die;
    
        /**
         * Create temporary image
         */
        $tmpImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
        /**
         * Calculate backgroud color
         */
        $backgroundColor    = trim($backgroundColor, '#');
        $backgroundColor    = str_split($backgroundColor, 2);
        $backgroundColor[0] = @hexdec($backgroundColor[0]);
        $backgroundColor[1] = @hexdec($backgroundColor[1]);
        $backgroundColor[2] = @hexdec($backgroundColor[2]);
        /**
         * Make background color to valid color
         */
        if ($backgroundColor[0] < 0 || $backgroundColor[0] > 255) {
            $backgroundColor[0] = 255;
        }
        if ($backgroundColor[1] < 0 || $backgroundColor[1] > 255) {
            $backgroundColor[1] = 255;
        }
        if ($backgroundColor[2] < 0 || $backgroundColor[2] > 255) {
            $backgroundColor[2] = 255;
        }
    
        if ('image/png' == $extension) {
            $col=imagecolorallocatealpha($tmpImg, $backgroundColor[0], $backgroundColor[1], $backgroundColor[2], 127);
            imagefill($tmpImg,0,0,$col);
            /**
             * Make new thumbnail
             */
            imagecopyresized($tmpImg, $img, $dstX, $dstY, 0, 0, $sWidth, $sHeight, $width, $height);
            
            imagealphablending($tmpImg,false);
            imagesavealpha($tmpImg,true);
        } else {
            $col=imagecolorallocatealpha($tmpImg, $backgroundColor[0], $backgroundColor[1], $backgroundColor[2], 0);
            imagefill($tmpImg,0,0,$col);
            /**
             * Make new thumbnail
             */
            imagecopyresized($tmpImg, $img, $dstX, $dstY, 0, 0, $sWidth, $sHeight, $width, $height);
        }
        
        /**
         * Save image to file
         */
        $imageFunc($tmpImg, "{$thumbImgPath}");
        
        return $thumbImgPath;
    }
    
    public static function cropImage($source, $thumbWidth = 2000) 
    {
        $source = urldecode($source);
        /**
         * Is invalid image?
         */
        if (! is_file($source)) {
            return $source;
        }
        $info = getimagesize($source);
        if ($thumbWidth >= $info[0]) {
            return $source;
        }
    
        $extension = strtolower($info['mime']);
        switch ($extension) {
            case 'image/jpeg':
                $imgFromFunc = 'imagecreatefromjpeg';
                $imageFunc   = 'imagejpeg';
                break;
            case 'image/png':
                $imgFromFunc = 'imagecreatefrompng';
                $imageFunc   = 'imagepng';
                break;
            case 'image/gif':
                $imgFromFunc = 'imagecreatefromgif';
                $imageFunc   = 'imagegif';
                break;
            default:
                return $source;
        }
        $img = $imgFromFunc("{$source}");
        // load image and get image size
        
        
        $thumbImgPath = "tmp/images/" . microtime() . rand(1, 1000000000) . ".jpg";
    
        $width = imagesx($img);
        $height = imagesy($img);
    
        // calculate thumbnail size
        $newWidth = $thumbWidth;
        $newHeight = floor($height * ( $thumbWidth / $width ));
    
        // create a new temporary image
        $tmpImg = imagecreatetruecolor($newWidth, $newHeight);
        
    
        if ('image/png' == $extension) {
            $col=imagecolorallocatealpha($tmpImg, 255, 255, 255, 127);
            imagefill($tmpImg,0,0,$col);
        }
    
        // copy and resize old image into new image
        imagecopyresized($tmpImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        // save thumbnail into a file
    
        if ('image/png' == $extension) {
            imagealphablending($tmpImg,false);
            imagesavealpha($tmpImg,true);
        }
        
        $imageFunc( $tmpImg,  "{$thumbImgPath}" );
        
        if (is_file("{$thumbImgPath}") && filesize("{$thumbImgPath}") >= 100) {
            copy("{$thumbImgPath}", "{$source}");
            unlink("{$thumbImgPath}");
        }
        return $source;
    }

    /**
     * Return image path from project folder
     * 
     * @param string $path
     * 
     * @example 
     * "/<your_project>/media/userfiles/images/example.jpg" >> "media/userfiles/images/example.jpg"
     */
    public static function getImagePath($path)
    {
        return substr($path, strlen(Nine_Registry::getBaseUrl()));
    }
    
	//Upload avatar
	public static function uploadHinh($directory, $imageName)
	{
		$upload = new Zend_File_Transfer_Adapter_Http();     
		$upload->setDestination($directory,$imageName);
		$upload->addValidator('ImageSize', false, array('minwidth' => 10, 
                                                        'maxwidth' => 800,
                                                        'minheight' => 10,
                                                        'maxheight' => 800));    
    	if(!$upload->isValid()){
    		return -1;
		}
        $newImageName = "cate_" . md5(time()).strstr($imageName, '.');
        $upload->addFilter('Rename', array('target'=> $directory . $newImageName,'overwrite' => true));
        $upload->receive($imageName);
       	return $newImageName;
   	}
   	
    public static function split_words($string, $nb_caracs, $separator){
	    $string = strip_tags(html_entity_decode($string));
	    if( strlen($string) <= $nb_caracs ){
	        $final_string = $string;
	    } else {
	        $final_string = "";
	        $words = explode(" ", $string);
	        foreach( $words as $value ){
	            if( strlen($final_string . " " . $value) < $nb_caracs ){
	                if( !empty($final_string) ) $final_string .= " ";
	                $final_string .= $value;
	            } else {
	                break;
	            }
	        }
	        $final_string .= $separator;
	    }
	    return $final_string;
	}
	
	public static function replace_specialchars($string)
	{
		$result=str_replace(array('\"',"\'"),array('"',"'"),$string);
		return $result;
	}

	//print_r(array_sort($people, 'age', SORT_DESC));
	public static function array_sort($array, $on, $order=SORT_ASC)
	{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
	}
	
	
	public static function genaratorcaptcha()
	{
		//Start------Khởi tạo mã captcha
	    $captcha = new Zend_Captcha_Image();
		$captcha	->setTimeout('300')
	                ->setWordLen('5')
	                ->setHeight('35')
	                ->setWidth('90')
	                ->setImgDir(dirname(dirname(dirname(__FILE__))) . '/media/captcha/images/')
	                ->setImgUrl('/captcha/images/')
	                ->setSuffix('.jpg')
	                ->setFont(dirname(dirname(dirname(__FILE__))) . '/media/captcha/font/jkasperville.ttf')
	                ->setFontSize('25')
	                ->setLineNoiseLevel('1')
	            	->setDotNoiseLevel('20')
	            	->setExpiration('1')
	           	 	->setGcFreq('1');
		$captcha->generate();
		return $captcha;
		
	}
	
	public static function del_space($str){
		$result = "";
		$str = trim($str," ");
		$character = str_split($str);
		for ($i = 0;$i < strlen($str);$i++)
		{
			if($character[$i]!=" ")
				$result.= $character[$i];
			if($character[$i]==" " && $character[$i+1]!=" ")
				$result.= $character[$i];
		}

		return $result;
	}
   	  	
	public static function movePage($num,$url){
	   static $http = array (
	       100 => "HTTP/1.1 100 Continue",
	       101 => "HTTP/1.1 101 Switching Protocols",
	       200 => "HTTP/1.1 200 OK",
	       201 => "HTTP/1.1 201 Created",
	       202 => "HTTP/1.1 202 Accepted",
	       203 => "HTTP/1.1 203 Non-Authoritative Information",
	       204 => "HTTP/1.1 204 No Content",
	       205 => "HTTP/1.1 205 Reset Content",
	       206 => "HTTP/1.1 206 Partial Content",
	       300 => "HTTP/1.1 300 Multiple Choices",
	       301 => "HTTP/1.1 301 Moved Permanently",
	       302 => "HTTP/1.1 302 Found",
	       303 => "HTTP/1.1 303 See Other",
	       304 => "HTTP/1.1 304 Not Modified",
	       305 => "HTTP/1.1 305 Use Proxy",
	       307 => "HTTP/1.1 307 Temporary Redirect",
	       400 => "HTTP/1.1 400 Bad Request",
	       401 => "HTTP/1.1 401 Unauthorized",
	       402 => "HTTP/1.1 402 Payment Required",
	       403 => "HTTP/1.1 403 Forbidden",
	       404 => "HTTP/1.1 404 Not Found",
	       405 => "HTTP/1.1 405 Method Not Allowed",
	       406 => "HTTP/1.1 406 Not Acceptable",
	       407 => "HTTP/1.1 407 Proxy Authentication Required",
	       408 => "HTTP/1.1 408 Request Time-out",
	       409 => "HTTP/1.1 409 Conflict",
	       410 => "HTTP/1.1 410 Gone",
	       411 => "HTTP/1.1 411 Length Required",
	       412 => "HTTP/1.1 412 Precondition Failed",
	       413 => "HTTP/1.1 413 Request Entity Too Large",
	       414 => "HTTP/1.1 414 Request-URI Too Large",
	       415 => "HTTP/1.1 415 Unsupported Media Type",
	       416 => "HTTP/1.1 416 Requested range not satisfiable",
	       417 => "HTTP/1.1 417 Expectation Failed",
	       500 => "HTTP/1.1 500 Internal Server Error",
	       501 => "HTTP/1.1 501 Not Implemented",
	       502 => "HTTP/1.1 502 Bad Gateway",
	       503 => "HTTP/1.1 503 Service Unavailable",
	       504 => "HTTP/1.1 504 Gateway Time-out"
	   );
	   header($http[$num]);
	   header ("Location: $url");
	}

	public static function curPageURL() {
		$pageURL = 'http';
		if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
		$pageURL .= "://";
		if ($_SERVER["SERVER_PORT"] != "80") {
		  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
		} else {
		  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		}
		return $pageURL;
	}
	public static function encodeBase64UrlSafe($value)
	{
	   return str_replace(array('+', '/'), array('-', '_'), base64_encode($value));
	}
	
	public static function decodeBase64UrlSafe($value)
	{
	   return base64_decode(str_replace(array('-', '_'), array('+', '/'), $value));
	}

    private function replaceTags($startPoint, $endPoint, $replacement, $source , $offset = 0) {
        $startTagPos = strrpos($source, $startPoint, $offset);
        $endTagPos = strrpos($source, $endPoint, $offset);

        if($startTagPos === false){
            return $source;
        }

        $newOffset = $startTagPos - strlen($source);

        $startTagPos += 3;
        
        $tagLength = $endTagPos - $startTagPos ;
        $text = substr_replace($source, $replacement, $startTagPos, $tagLength);
        return $this->replaceTags($startPoint, $endPoint, $replacement, $text, $newOffset);
    }		
}